package com.xuxin.baby.page;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.xuxin.baby.R;
import com.xuxin.baby.activity.UserDataActivity;
import com.xuxin.baby.activity.UserHistoryActivity;
import com.xuxin.baby.activity.UserLikeActivity;
import com.xuxin.baby.activity.UserNoticeActivity;
import com.xuxin.baby.activity.UserRechargeActivity;
import com.xuxin.baby.activity.UserSignActivity;
import com.xuxin.baby.activity.UserTicketActivity;
import com.xuxin.baby.activity.UserVipActivity;
import com.xuxin.baby.adapter.UserExtendAdapter;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.base.BaseFragment;
import com.xuxin.baby.bean.BaseBean;
import com.xuxin.baby.bean.UserDataBean;
import com.xuxin.baby.contract.UserContract;
import com.xuxin.baby.event.BaseEventFragment;
import com.xuxin.baby.event.MainFragmentEvent;
import com.xuxin.baby.event.UserFragmentEvent;
import com.xuxin.baby.glide.GlideApp;
import com.xuxin.baby.listener.OnUserExtendListener;
import com.xuxin.baby.network.Retrofit;
import com.xuxin.baby.presenter.UserPresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.RecycleUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 个人中心
 */
public class UserFragment extends BaseEventFragment implements UserContract.View {
    private final UserContract.Presenter presenter = new UserPresenter(this);
    RequestOptions options = RequestOptions.bitmapTransform(new CircleCrop());
    @BindView(R.id.user_image)
    ImageView user_image;//头像
    @BindView(R.id.user_name)
    TextView user_name;//用户名
    @BindView(R.id.user_points)
    TextView user_points;//积分
    @BindView(R.id.user_grade)
    TextView user_grade;//会员等级
    @BindView(R.id.user_beans)
    TextView user_beans;//余额宝宝豆
    @BindView(R.id.user_refresh)
    SmartRefreshLayout user_refresh;
    @BindView(R.id.user_recycle_extend)
    RecyclerView user_recycle_extend;//扩展功能

    private String memberId;//用户id
    private String tenantId;//租户id
    private String token;//授权token

    public static UserFragment newInstance() {
        return new UserFragment();
    }

    @Override
    public View setContentView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        return inflater.inflate(R.layout.fragment_user, container, false);
    }

    @Override
    public void initView() {
        //功能列表
        user_refresh.setEnableLoadMore(false);
        user_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                handler.sendEmptyMessage(0);
            }
        });
        RecycleUtils.init(user_recycle_extend, 2);
        UserExtendAdapter myAdapter = new UserExtendAdapter();
        user_recycle_extend.setAdapter(myAdapter);
        myAdapter.setOnItemClickListener(new OnUserExtendListener());
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(getContext());
        memberId = aCache.getAsString(BaseConstant.memberId);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        handler.sendEmptyMessage(0);
    }

    @Override
    public void onComplete() {
        user_refresh.finishRefresh();
        user_refresh.finishLoadMore();
    }

    @Override
    @OnClick({R.id.user_data, R.id.user_like,
            R.id.user_history, R.id.user_notice,
            R.id.user_sign, R.id.user_vip,
            R.id.user_ticket, R.id.user_recharge})
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.user_data) {
            ActivityUtils.startActivityForResult(this, UserDataActivity.class, 200);
        } else if (id == R.id.user_like) {
            ActivityUtils.startActivity(UserLikeActivity.class);
        } else if (id == R.id.user_history) {
            ActivityUtils.startActivity(UserHistoryActivity.class);
        } else if (id == R.id.user_notice) {
            ActivityUtils.startActivity(UserNoticeActivity.class);
        } else if (id == R.id.user_sign) {
            ActivityUtils.startActivity(UserSignActivity.class);
        } else if (id == R.id.user_vip) {
            ActivityUtils.startActivity(UserVipActivity.class);
        } else if (id == R.id.user_ticket) {
            ActivityUtils.startActivity(UserTicketActivity.class);
        } else if (id == R.id.user_recharge) {
            ActivityUtils.startActivity(UserRechargeActivity.class);
        }
    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {//个人信息
                presenter.getUserData(tenantId, token, memberId);
            }
            return false;
        }
    });

    @Override
    public void onSuccess(UserDataBean userDataBean) {
        if (null != userDataBean.getResult()) {
            if (!StringUtils.isEmpty(userDataBean.getResult().getNickname())) {
                user_name.setText(userDataBean.getResult().getNickname());
            } else {
                user_name.setText(userDataBean.getResult().getLoginName());
            }
            user_points.setText(String.valueOf(userDataBean.getResult().getPoints()));
            user_grade.setText(String.valueOf(userDataBean.getResult().getGrade()));
            user_beans.setText(String.format("宝宝豆：%s", userDataBean.getResult().getBeans()));
            /**
             * 加载图片
             */
            String userImage = Retrofit.image_url + userDataBean.getResult().getAvatar();
            LogUtils.e("个人中心_image = " + userImage);
            GlideApp.with(context).load(userImage).placeholder(R.mipmap.img_placeholder_head).apply(options).into(user_image);
        }
    }

    @Override
    public void onImageSuccess(BaseBean baseBean) {

    }

    @Override
    public void onSuccess(BaseBean baseBean) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 200) {
            LogUtils.e("刷新我的");
            handler.sendEmptyMessage(0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UserFragmentEvent event) {
        LogUtils.e("刷新我的");
        handler.sendEmptyMessage(0);
    }
}